package com.zyh.server.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class OSSService {

	@Autowired
	private OSSConfig ossConfig;

	public String uploadFile(String type, MultipartFile file) {
		String fileUrl = "";
		OSS ossClient = new OSSClientBuilder().
				build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
		// 设置存储空间的读写权限。例如将examplebucket的读写权限ACL设置为私有Private。
		ossClient.setBucketAcl(ossConfig.getBucketName(), CannedAccessControlList.PublicReadWrite);
		try {
			// 创建一个“伪目录”对象，即在目录末尾加上斜线。
			// 这里创建的是名为"type/"的目录。
			ossClient.putObject(ossConfig.getBucketName(), type + "/", new ByteArrayInputStream(new byte[0]));
			System.out.println("目录创建成功! created.");

			String fileName = type+"/"+System.currentTimeMillis() + "_" + file.getOriginalFilename();
			InputStream inputStream = file.getInputStream();
			ossClient.putObject(ossConfig.getBucketName(), fileName, inputStream);
			fileUrl = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" +fileName;
			//            `type` 图片类型，可选值如下。
			//            - `user_avatar` 用户头像
			//            - `goods_picture` 商品图
			//            - `goods_description` 商品描述图

		} catch (OSSException | IOException e) {
			throw new RuntimeException("上传文件到 OSS 失败", e);
		} finally {
			ossClient.shutdown();
		}
		return fileUrl;
	}
}

